package com.wangzhixuan.apiController;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.wangzhixuan.commons.base.ApiBaseController;
import com.wangzhixuan.commons.constant.ApiCode;
import com.wangzhixuan.commons.easemob.Entry;
import com.wangzhixuan.commons.easemob.service.TalkDataService;
import com.wangzhixuan.commons.shiro.PasswordHash;
import com.wangzhixuan.commons.sms.JavaSmsApi;
import com.wangzhixuan.commons.utils.StringUtils;
import com.wangzhixuan.commons.utils.UUIDGenerator;
import com.wangzhixuan.model.User;
import com.wangzhixuan.service.IDictionaryService;
import com.wangzhixuan.service.IUserService;

/**
 * @description：用户管理
 * @author：zhixuan.wang
 * @date：2015/10/1 14:51
 */
//@CrossOrigin(origins = "*")当前版本1.7 会报错，原因版本太低 http://spring.io/guides/gs/rest-service-cors/
@Controller
@RequestMapping("api/user")
public class UserApiController extends ApiBaseController {
	
    @Autowired
    private IUserService userService;
    @Autowired
    private PasswordHash passwordHash;
    
    @Autowired
    private IDictionaryService dictionaryService;
    
    @Autowired
	private CacheManager cacheManager;

    @RequestMapping("/login")
    @ResponseBody
    public Object loginPost(String username, String password) {
        logger.info("POST请求登录");
        if (StringUtils.isBlank(username)) {
            return renderError(ApiCode.CODE_501, "用户名不能为空");
        }
        if (StringUtils.isBlank(password)) {
            return renderError(ApiCode.CODE_501, "密码不能为空");
        }
        User user = userService.getUserByPhone(username);
        if(user==null){
        	return renderError(ApiCode.CODE_1303, "账号不存在");
        }
        if(user.getStatus()!=0){
        	return renderError(ApiCode.CODE_1304, "账号未启用");
        }
        String pwd = passwordHash.toHex(password, user.getSalt());
        if(user.getPassword().equals(pwd)){
        	Map<String,Object> retMap = new HashMap<String,Object>();
        	retMap.put("userId", user.getId()+"");
        	retMap.put("userNo", user.getLoginName());
        	retMap.put("name", user.getName());
        	retMap.put("headPic", user.getHeadPortrait());
        	String token = UUIDGenerator.getUUID();
        	retMap.put("token", token);
        	return renderSuccess(ApiCode.CODE_200, "登陆成功",retMap);
        }
        return renderError(ApiCode.CODE_1305, "密码错误");
    }
    
	@RequestMapping("/getUserinfo")
    @ResponseBody
    public Object getUserinfo(Integer userId) {
		if (userId==null) {
            return renderError(ApiCode.CODE_501, "用户ID不能为空");
        }
    	Map<String,Object> map = userService.selectUserById(userId);	
        return renderSuccess(ApiCode.CODE_200, "成功",map==null?"":map);
    }
	
	@RequestMapping("/Contacts")
    @ResponseBody
    public Object Contacts() {
    	List<Map<String,Object>> retList = userService.selectContacts();	
        return renderSuccess(ApiCode.CODE_200, "成功",retList);
    }
       
    @SuppressWarnings("unchecked")
	@RequestMapping("/sendSms")
    @ResponseBody
    public Object sendSms(String phoneNum) throws IOException {
    	if (StringUtils.isBlank(phoneNum)) {
            return renderError(ApiCode.CODE_501, "手机号码不能为空");
        }
    	int random = (int)((Math.random()*9+1)*100000);
    	String content ="【聚特易】欢迎使用聚特易，您的手机验证码是"+random+"，有效期为10分钟，请尽快验证。";
    	String result = JavaSmsApi.sendSms(JavaSmsApi.getApiKey(), content, phoneNum);
    	//{"code":0,"msg":"发送成功","count":1,"fee":0.055,"unit":"RMB","mobile":"13530129494","sid":7624632862}
    	Map<String,Object> map = JSON.parseObject(result,Map.class);
    	int code = (Integer)map.get("code");
        if(code == 0){
        	Element element = new Element(phoneNum, random); 
        	cacheManager.getCache("sms").put(element);
        	element = cacheManager.getCache("sms").get(phoneNum);
        	return renderSuccess(ApiCode.CODE_200, "成功发送短信验证码.");
        }else{
        	return renderError(ApiCode.CODE_1306, "发送短信验证码失败.");
        }
    }
	
	@RequestMapping("/modifyPwd")
    @ResponseBody
    public Object  modifyPwd(String phoneNum,String verificationCode,String newPassword) throws Exception{
		if (StringUtils.isBlank(phoneNum)) {
            return renderError(ApiCode.CODE_501, "手机号码不能为空");
        }
		if (StringUtils.isBlank(verificationCode)) {
            return renderError(ApiCode.CODE_501, "验证码不能为空");
        }
		if (StringUtils.isBlank(phoneNum)) {
            return renderError(ApiCode.CODE_501, "新密码不能为空");
        }
    	Element element = cacheManager.getCache("sms").get(phoneNum);
        if(element!=null){
        	if(verificationCode.equals(element.getObjectValue())){
        		User user = userService.getUserByPhone(phoneNum);
        		if(user!=null){
        			String salt = user.getSalt();
        			userService.updatePwdByUserId(user.getId(), passwordHash.toHex(newPassword, salt));
        			return renderSuccess(ApiCode.CODE_200, "重置成功.");
        		}
        		return renderError(ApiCode.CODE_1309, "重置失败.");
        	}
        	return renderError(ApiCode.CODE_1309, "重置失败.");
        }
        return renderError(ApiCode.CODE_1307, "验证码过期.");
    }
	
	@RequestMapping("/delete")
    @ResponseBody
    public Object delete(Integer userId) {
		if (userId==null) {
            return renderError(ApiCode.CODE_501, "用户ID不能为空");
        }
        boolean b = userService.deleteById(userId);
		if (b) {
			return renderSuccess(ApiCode.CODE_200, "删除成功！");
		} else {
			return renderError(ApiCode.CODE_500, "删除失败！");
		}
    }
	
	@RequestMapping("/modify")
    @ResponseBody
    public Object modify(Integer userId,String userName,String headPortrait) throws Exception {
		if (userId==null) {
            return renderError(ApiCode.CODE_501, "网络异常，请重新登录");
        }
		if (userName==null) {
            return renderError(ApiCode.CODE_501, "网络出差了，稍后再试");
        }
		if (headPortrait==null) {
            return renderError(ApiCode.CODE_501, "请添加头像");
        }
        User user = userService.selectById(userId);
        String phone = user.getPhone();
        user.setName(userName);
        user.setHeadPortrait(headPortrait);
        TalkDataService service = Entry.getInstance().getTalkApi();
        service.userModifyNickname(phone, userName);
        boolean b = userService.updateById(user);
		if (b) {
			return renderSuccess(ApiCode.CODE_200, "更新成功！");
		} else {
			return renderError(ApiCode.CODE_500, "更新失败！");
		}
    }
	
}
